package com.education.admin.api.shiro;

import com.education.common.exception.BusinessException;
import com.education.common.model.AdminUserSession;
import com.education.common.utils.EncryptUtil;
import com.education.common.utils.ObjectUtils;
import com.education.common.utils.SpringBeanManager;
import com.education.mapper.system.SystemAdminMapper;
import com.education.service.system.SystemAdminService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author 余一
 * @Description
 * @date 2021/6/27 17:38
 */
@Component
public class SystemRealm extends AuthorizingRealm {

    /**
     * 满足以下三点时调用：
     * 1.用户登录成功
     * 2.缓存中没有用户权限
     * 3.访问的接口使用到了shiro提供的权限注解
     * 用户授权，加载角色和权限，配置了缓存管理器时，该方法只会调用一次
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SystemAdminService adminService = SpringBeanManager.getBean(SystemAdminService.class);
        AdminUserSession adminUserSession = adminService.getAdminUserSession();
        if (ObjectUtils.isNotEmpty(adminUserSession)) {
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            simpleAuthorizationInfo.addStringPermissions(adminUserSession.getPermissionList());
            return simpleAuthorizationInfo;
        }
        return null;
    }

    /**
     * 用户认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token= (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        SystemAdminMapper systemAdminMapper = SpringBeanManager.getBean(SystemAdminMapper.class);
        Map userInfoMap = systemAdminMapper.findByLoginName(username);
        Boolean isDisabled = ((Integer)userInfoMap.get("disabled_flag") == 0) ? false : true;
        if (ObjectUtils.isEmpty(userInfoMap)) {
            throw new UnknownAccountException("用户不存在");
        }else if (isDisabled){
            throw new BusinessException("该用户已被禁用");
        }
        //加密用户输入的密码，再通过shiro核对是否和数据库的用户密码一致
        String password = EncryptUtil.getMd5(new String(token.getPassword()), (String) userInfoMap.get("encrypt"));
        token.setPassword(password.toCharArray());
        return new SimpleAuthenticationInfo(new AdminUserSession(userInfoMap),userInfoMap.get("password"),getName());
    }
}
